package com.yjj.im.ui;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.reflect.TypeToken;
import com.yjj.im.R;
import com.yjj.im.Utils.AFinalHttp;
import com.yjj.im.Utils.BlutetoothPrinterUtils;
import com.yjj.im.Utils.DeviceInfoUtils;
import com.yjj.im.Utils.DialogUtil;
import com.yjj.im.Utils.GsonFomater;
import com.yjj.im.Utils.HandlerUtils;
import com.yjj.im.Utils.Utils;

import androidx.annotation.NonNull;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.yjj.im.Utils.XpsdkPrintApiDemoTest;
import com.yjj.im.bean.Carbean;
import com.yjj.im.bean.DataBean;
import com.yjj.im.bean.ResultBean;
import com.yjj.im.ui.PopupMenu.MENUITEM;
import com.yjj.im.ui.PopupMenu.OnItemClickListener;

import net.xpyun.printeropen.service.ResponseListener;
import net.xpyun.printeropen.util.GsonUtils;
import net.xpyun.printeropen.vo.ObjectRestResponse;

import butterknife.BindView;
import butterknife.ButterKnife;


public class MainActivity extends Activity {
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_item)
    TextView tv_item;
    @BindView(R.id.tv_item1)
    TextView tv_item1;
    @BindView(R.id.tv_item2)
    TextView tv_item2;
    @BindView(R.id.tv_item3)
    TextView tv_item3;
    @BindView(R.id.tv_item4)
    TextView tv_item4;
    @BindView(R.id.tv_item5)
    TextView tv_item5;
    @BindView(R.id.tv_item6)
    TextView tv_item6;
    @BindView(R.id.tv_item7)
    TextView tv_item7;
    @BindView(R.id.tv_item8)
    TextView tv_item8;
    @BindView(R.id.tv_item9)
    TextView tv_item9;
    @BindView(R.id.tv_item10)
    TextView tv_item10;
    @BindView(R.id.value_item)
    TextView value_item;
    @BindView(R.id.value_item1)
    TextView value_item1;
    @BindView(R.id.value_item2)
    TextView value_item2;
    @BindView(R.id.value_item3)
    TextView value_item3;
    @BindView(R.id.value_item4)
    TextView value_item4;
    @BindView(R.id.value_item5)
    TextView value_item5;
    @BindView(R.id.value_item6)
    TextView value_item6;
    @BindView(R.id.value_item7)
    TextView value_item7;
    @BindView(R.id.value_item8)
    TextView value_item8;
    @BindView(R.id.value_item9)
    TextView value_item9;
    @BindView(R.id.value_item10)
    TextView value_item10;
    private Button btnMain;
    private RecyclerView mRecyclerView;
    private MyAdapter mMyAdapter;
    private ImageView iv_menu,iv_back;
    private PopupMenu popupMenu;
    private int which = 99;
    private Handler handler;
    private int totalCount= 0;
    private int current = 0;
    private ArrayList<DataBean> list = new ArrayList<>();
    private Context context;
    private BlutetoothPrinterUtils blutetoothPrinterUtils;
    private HandlerUtils.PrinterHandler mPrinterHandler;
    private LinearLayout promptView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        blutetoothPrinterUtils = new BlutetoothPrinterUtils();
        initView();
        promptView = findViewById(R.id.prompt_view);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1) {
                    mMyAdapter.notifyDataSetChanged();
                } else if(msg.what == 2) {

                } else if(msg.what == 3) {

                }else if(msg.what == 4){

                }else if(msg.what == 5){

                }else if(msg.what == 6){

                }
            }
        };
        DialogUtil.getInstance().show(context, "正在加载...",null);
        LoadData(0,MessageActivity.currentId);
        mPrinterHandler = new HandlerUtils.PrinterHandler(blutetoothPrinterUtils.mHandlerIntent);
        BlutetoothPrinterUtils.setPriterHadler(mPrinterHandler);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter printerStatusFilter = new IntentFilter();
        printerStatusFilter.addAction(blutetoothPrinterUtils.PRINTER_NORMAL_ACTION);
        printerStatusFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        printerStatusFilter.addAction(blutetoothPrinterUtils.GET_CUST_PRINTAPP_PACKAGENAME_ACTION);

        registerReceiver(blutetoothPrinterUtils.IPosPrinterStatusListener,printerStatusFilter);

//        loopPrintFlag = DEFAULT_LOOP_PRINT;
        blutetoothPrinterUtils.LoadBluetoothPrinter();
    }

    private void initView() {
        ButterKnife.bind(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_main);
//        String[] data = new String[10];
        popupMenu = new PopupMenu(this);
        tv_title.setText("称重结果");
        iv_menu = (ImageView) findViewById(R.id.iv_menu);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        iv_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupMenu.showLocation(R.id.iv_menu);// 设置弹出菜单弹出的位置
                // 设置回调监听，获取点击事件
                popupMenu.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onClick(MENUITEM item, String str) {
                        // TODO Auto-generated method stub
                        Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
                        if(item == MENUITEM.ITEM1){
                            which = 99;
                            current = 0;
                        }else if(item == MENUITEM.ITEM2){
                            which = 98;
                            current= 0;
                        }
                        list.clear();
                        LoadData(current,MessageActivity.currentId);
                    }
                });
            }
        });
        mMyAdapter = new MyAdapter(this, list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        ((LinearLayoutManager) layoutManager).setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mMyAdapter);
        mMyAdapter.setonItemClickListener(new MyAdapter.onItemClickListener() {
            @Override
            public void onItemClick(int position) {

                showConfirmDialog(position);
            }
        });
        mRecyclerView.addOnLayoutChangeListener(new RecyclerView.OnLayoutChangeListener(){
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom){
                Log.e("baoshan","oldBottom :["+oldBottom);
            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
    Log.e("baoshan","newState :["+newState);
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        // 滚动状态为空闲

                        // 执行相应的操作
                    } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                        // 滚动状态为拖拽

                        // 执行相应的操作
                    } else if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                        // 滚动状态为自动滚动

                        // 执行相应的操作
                    }
                }

                  @Override
                  public void onScrolled(@NonNull RecyclerView reclerView, int dx, int dy) {
                      super.onScrolled(reclerView, dx, dy);
                      if(!reclerView.canScrollVertically(1)){
                          Log.e("baoshan","dy:{"+dy+"");
                          LoadData(current,MessageActivity.currentId);
                      }

                  }



                                          }



            );


        btnMain = (Button) findViewById(R.id.btn_main);
        btnMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mMyAdapter.data[0] = "0000000";
//                mMyAdapter.data[2] = "2222222";
//                mMyAdapter.notifyItemChanged(0);
//                mMyAdapter.notifyItemChanged(2);
            }
        });
    }

    private void LoadData(int start,String clientId){
        Log.e("baoshan","LoadData");
        String url = "http://"+MessageActivity.baseUrl+"/mqttmsg.do?which="+which+"&start="+current*10+"&view=json";
        Map<String, String> params = new HashMap<>();
        params.put("mqttMsg.clientid",clientId);
        params.put("start",start*10+"");
        params.put("which",which+"");
        params.put("view","json");
        AFinalHttp.requestForGet(url, params, null,new AFinalHttp.CallBack(this) {

            @Override
            protected void success(Object data) {
                String ss = data.toString();
                if(ss != null){
                    ResultBean  resultBean = GsonFomater.format(ss,ResultBean.class);
                    totalCount = resultBean.totalCount;
                    if(resultBean != null && resultBean.result != null && resultBean.result.size() >0){
                        if(list.size() < totalCount){
                            list.addAll(resultBean.result);
                            current++;
                        }
                    }
                }

                Log.e("baoshan","获取下页数据成功：【"+ss+"]");
//                parsedata(data.toString(),idList,nameList);
//                if(nameList!= null && nameList.size() >0){
//
                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
//                }
//                else {
//                    Utils.toast("获取数据成功");
//                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg){
                Log.e("baoshann",strMsg);
            }
        });
    }

    private void showConfirmDialog( int position) {
        new com.hd.chat.widget.CDialog.Builder(this)
                .setCancel("取消")
                .setMessage("确定补打小票吗")
                .setConfirm("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DataBean dataBean =  list.get(position);
                        dataToView(dataBean);
                    }
                }).build().show();
    }
    private Bitmap viewToBitmap(View v){
        int width = v.getWidth();
        int height = v.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        v.draw(canvas);
        return bitmap;
    }
    public String saveImg(View view) {
        Bitmap cachebmp = viewToBitmap(view);
        blutetoothPrinterUtils.printBitmapTest(cachebmp);
//        try {
//            String dir=
//                    Environment.getExternalStorageDirectory().getAbsolutePath()+"/share.png";
//            File f = new File(dir);
//            isGrantExternalRW(this);
//            if (!f.exists()) {
//                f.getParentFile().mkdirs();
//                f.createNewFile();
//            }
//            FileOutputStream out = new FileOutputStream(f);
//            cachebmp.compress(Bitmap.CompressFormat.PNG, 90, out);
//            out.flush();
//            out.close();
//            view.destroyDrawingCache();
//            return f.getAbsolutePath();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return null;
    }

    private void dataToView(DataBean resultBean){
        Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/fangsong.ttf");
        Typeface typeface1 = Typeface.createFromAsset(getAssets(), "fonts/jianti.ttf");

//使用字体成仿宋体
        tv_item.setTypeface(typeface);
        tv_item1.setTypeface(typeface);
        tv_item2.setTypeface(typeface);
        tv_item3.setTypeface(typeface);
        tv_item4.setTypeface(typeface);
        tv_item5.setTypeface(typeface);
        tv_item6.setTypeface(typeface);
        tv_item7.setTypeface(typeface);
        tv_item8.setTypeface(typeface);
        tv_item9.setTypeface(typeface);
        tv_item10.setTypeface(typeface);
        value_item.setTypeface(typeface1);
        value_item1.setTypeface(typeface1);
        value_item2.setTypeface(typeface1);
        value_item3.setTypeface(typeface1);
        value_item4.setTypeface(typeface1);
        value_item5.setTypeface(typeface1);
        value_item6.setTypeface(typeface1);
        value_item7.setTypeface(typeface1);
        value_item8.setTypeface(typeface1);
        value_item9.setTypeface(typeface1);
        value_item10.setTypeface(typeface1);
        String company = MessageActivity.compayKeyList.get(resultBean.company);
        String company1 = MessageActivity.compayKeyList.get(resultBean.company2);
        String product = MessageActivity.compayKeyList.get(resultBean.product);
        value_item.setText(company);
        value_item1.setText(company1);
        value_item2.setText(product);
        value_item3.setText(resultBean.weight2+"");
        value_item4.setText(resultBean.weight1+"");

            value_item5.setText(resultBean.weight1-resultBean.weight2+"");

//        value_item5.setText(resultBean.result.get(0).weight1-resultBean.result.get(0).weight2+"");
        value_item6.setText(resultBean.car);
        value_item7.setText(resultBean.company);
        value_item8.setText(resultBean.note);
        value_item9.setText(resultBean.cserial);
        value_item10.setText(resultBean.ctime);
//        promptView
//        viewToBitmap(promptView);
        String deviceInfo = DeviceInfoUtils.getDeviceManufacturer();
        if("alps".equals(deviceInfo)){
            saveImg(promptView);
        }else {
            printResult(resultBean.cserial);
//            try {
//                XpsdkPrintApiDemoTest xpsdkPrintApiDemoTest = new XpsdkPrintApiDemoTest();
//                xpsdkPrintApiDemoTest.printComplexReceipt(resultBean,new ResponseListener() {
//                    @Override
//                    public void onFail(IOException e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onResponse(String s) {
//                        ObjectRestResponse<String> resp = GsonUtils.fromJson(s,
//                                new TypeToken<ObjectRestResponse<String>>() {}.getType());
//                        runOnUiThread(new Runnable() {
//                            public void run() {
//                                if (resp.getCode() == 0) {
//                                    final Toast toast = Toast.makeText(MainActivity.this, resp.getData(), Toast.LENGTH_SHORT);
//                                } else {
//                                    final Toast toast = Toast.makeText(MainActivity.this, resp.getMsg(), Toast.LENGTH_SHORT);
//                                }
//                            }
//                        });
//                    }
//                });
//            } catch (Exception ex){
//                ex.printStackTrace();
//            }
        }


    }
    private void printResult(String cserial){
        Log.e("baoshan","printResult");
        String url = "http://"+MessageActivity.baseUrl+"/mqttmsg!print.do?cserial="+cserial;
        Map<String, String> params = new HashMap<>();

        params.put("view","json");
        AFinalHttp.requestForGet(url, params, null,new AFinalHttp.CallBack(this) {

            @Override
            protected void success(Object data) {
                String ss = data.toString();
                if(ss != null){
                    ResultBean  resultBean = GsonFomater.format(ss,ResultBean.class);
                    totalCount = resultBean.totalCount;
                    if(resultBean != null && resultBean.success){
                        Toast.makeText(MainActivity.this, "打印成功", Toast.LENGTH_LONG).show();
                    }
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg){
                Log.e("baoshann",strMsg);
            }
        });
    }


}
